package com.supply.dl.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.supply.dl.R;
import com.supply.dl.app.ApiService;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.adapter.NormalPositionAdapter;
import com.supply.dl.app.adapter.ViewHolder;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.app.http.BaseObserver;
import com.supply.dl.app.http.HttpMethod;
import com.supply.dl.app.http.RxSchedulers;
import com.supply.dl.bean.SaveTfOrderResult;
import com.supply.dl.bean.SelectDictionaryBean;
import com.supply.dl.bean.TfOrderDetail;
import com.supply.dl.bean.request.SaveTfOrderReq;
import com.supply.dl.utils.DialogUtils;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建移库单
 * <p>
 * Author: tian <br>
 * Time: 2018/6/13 11:06
 */
public class CreateMoveWareHouseSheetActivity extends BaseActivity {

    @BindView(R.id.material_rc)
    RecyclerView material_rc;

    /**
     * 移库原因
     */
    @BindView(R.id.yiku_reason_et)
    EditText yiku_reason_et;

    /**
     * 订单类型
     */
    @BindView(R.id.order_status_tv)
    TextView order_status_tv;

    /**
     * 出库仓库
     *
     *
     *
     */
    @BindView(R.id.out_tv)
    TextView out_tv;

    /**
     * 入库仓库
     */
    @BindView(R.id.in_tv)
    TextView in_tv;

    private NormalPositionAdapter<TfOrderDetail> adapter;

    private List<TfOrderDetail> datas;

    /**
     * 当前进行物料选择的对象
     */
    private TfOrderDetail currentSkuInfo;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_create_move_warehouse_sheet;
    }

    @Override
    protected void initView() {
        showLeftBack();
        setTitleShow("新建移库单");

        datas = new ArrayList<>();
        datas.add(new TfOrderDetail("", ""));

        adapter = new NormalPositionAdapter<TfOrderDetail>(this, datas) {
            @Override
            protected void convert(ViewHolder holder, final TfOrderDetail data, int position) {
                TextView code_tv = holder.getView(R.id.code_tv);
                EditText count_et = holder.getView(R.id.count_et);
                EditText weight_et = holder.getView(R.id.weight_et);
                EditText volume_et = holder.getView(R.id.volume_et);

                code_tv.setText(StringUtils.isCanUse(data.getSkuCode()) ?
                        "物料编码:" + data.getSkuCode() : "物料编码");

                holder.setText(R.id.name_tv, StringUtils.isCanUse(data.getSkuName()) ?
                        "物料名字:" + data.getSkuName() : "物料名字");

                holder.setText(R.id.material_name_tv, "物料" + (position + 1));

                count_et.setText(StringUtils.isCanUse(data.getAmount()) ? data.getAmount() : "");
                weight_et.setText(StringUtils.isCanUse(data.getWeight()) ? data.getWeight() : "");
                volume_et.setText(StringUtils.isCanUse(data.getVolume()) ? data.getVolume() : "");

                //跳转进行编码选择
                code_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        currentSkuInfo = data;

                        Intent intent = new Intent(CreateMoveWareHouseSheetActivity.this, MaterialSelectActivity.class);
                        startActivityForResult(intent, AppConfig.BaseDataAction.REQCODE_CHANGE_WL);
                    }
                });

                count_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (StringUtils.isCanUse(s.toString()))
                            data.setAmount(s.toString());
                    }
                });

                weight_et.addTextChangedListener(new TextWatcher() {
                    @Override


                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (StringUtils.isCanUse(s.toString()))
                            data.setWeight(s.toString());
                    }
                });

                volume_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (StringUtils.isCanUse(s.toString()))
                            data.setVolume(s.toString());
                    }
                });

                holder.getView(R.id.delete_tv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtils.showDialog(CreateMoveWareHouseSheetActivity.this, "提示", "确定删除当前物料吗?", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                datas.remove(data);
                                adapter.notifyDataSetChanged();
                            }
                        }).show();
                    }
                });
            }

            @Override
            protected int getItemLayoutId() {
                return R.layout.item_create_move_warehouse_sheet;
            }
        };

        material_rc.setLayoutManager(new LinearLayoutManager(this));
        material_rc.setAdapter(adapter);
    }


    @OnClick({R.id.out_rv, R.id.in_rv, R.id.add_material_tv, R.id.yi_ku_order_status_rl, R.id.save_tv})
    public void OnClick(View v) {

        if (v.getId() == R.id.save_tv) {
            if (checkInput())
                saveTfOrder();
            return;
        }

        if (v.getId() == R.id.add_material_tv) {
            Intent intent = new Intent(this, MaterialSelectActivity.class);
            startActivityForResult(intent, AppConfig.BaseDataAction.REQCODE_ADD_WL);
            return;
        }

        Intent intent = new Intent(this, SelectBaseDataActivity.class);
        String action = "";
        int reqCode = -1;

        switch (v.getId()) {

            case R.id.yi_ku_order_status_rl:
                action = AppConfig.BaseDataAction.STO_ASN_NOTICE_ORDER_ORDER_STATUS;
                reqCode = AppConfig.BaseDataAction.REQCODE_STATUS_SELECT;
                break;

            case R.id.out_rv:
                action = AppConfig.BaseDataAction.WARE_HOUSE_TYPE_1;
                reqCode = AppConfig.BaseDataAction.REQCODE_MOVE_OUT_HOUSE_SELECT;
                break;

            case R.id.in_rv:
                action = AppConfig.BaseDataAction.WARE_HOUSE_TYPE_0;
                reqCode = AppConfig.BaseDataAction.REQCODE_MOVE_IN_HOUSE_SELECT;
                break;
        }

        intent.putExtra("action", action);
        startActivityForResult(intent, reqCode);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data == null || data.getSerializableExtra("selectBean") == null)
            return;

        SelectDictionaryBean selectBean = (SelectDictionaryBean) data.getSerializableExtra("selectBean");

        switch (requestCode) {
            case AppConfig.BaseDataAction.REQCODE_STATUS_SELECT:
                order_status_tv.setText(selectBean.getText());
                order_status_tv.setTag(selectBean);
                break;
            case AppConfig.BaseDataAction.REQCODE_MOVE_OUT_HOUSE_SELECT:
                out_tv.setText(selectBean.getText());
                out_tv.setTag(selectBean);

                break;
            case AppConfig.BaseDataAction.REQCODE_MOVE_IN_HOUSE_SELECT:
                in_tv.setText(selectBean.getText());
                in_tv.setTag(selectBean);
                break;

            //物料切换
            case AppConfig.BaseDataAction.REQCODE_CHANGE_WL:

                if (currentSkuInfo == null)
                    return;

                currentSkuInfo.setSkuId(selectBean.getValue());
                currentSkuInfo.setSkuName(selectBean.getText());
                currentSkuInfo.setSkuCode(selectBean.getCode());
                currentSkuInfo.setAmount("");
                currentSkuInfo.setVolume("");
                currentSkuInfo.setWeight("");
                adapter.notifyDataSetChanged();

                currentSkuInfo = null;

                break;

            //新增物料
            case AppConfig.BaseDataAction.REQCODE_ADD_WL:
                datas.add(new TfOrderDetail(selectBean.getCode(), selectBean.getText()));
                adapter.notifyDataSetChanged();
                break;
        }
    }

    /**
     * 输入检查
     *
     * @return
     */
    private boolean checkInput() {

        if (order_status_tv.getTag() == null) {
            Toast.makeText(this, "请选择订单类型", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (out_tv.getTag() == null) {
            Toast.makeText(this, "请选择出库仓库", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (in_tv.getTag() == null) {
            Toast.makeText(this, "请选择入库仓库", Toast.LENGTH_SHORT).show();
            return false;
        }

        boolean isHasMaterail = false;

        for (TfOrderDetail item : datas) {
            if (StringUtils.isCanUse(item.getSkuCode())) {
                isHasMaterail = true;


                break;
            }
        }

        if (!isHasMaterail) {
            Toast.makeText(this, "请选择物料", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    /**
     * 提交数据
     */
    private void saveTfOrder() {
        SaveTfOrderReq req = new SaveTfOrderReq();

        req.orderType = ((SelectDictionaryBean) order_status_tv.getTag()).getValue();
        req.stoOutWhId = ((SelectDictionaryBean) out_tv.getTag()).getValue();
        req.stoInWhId = ((SelectDictionaryBean) in_tv.getTag()).getValue();

        if (StringUtils.isCanUse(yiku_reason_et.getText().toString()))
            req.traReason = yiku_reason_et.getText().toString();

        req.tfOrderDetails = datas;

        //开始进行网络的访问
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        mApiService.saveTfOrder(req)
                .compose(RxSchedulers.<BaseInfo>compose(this))
                .subscribe(new BaseObserver<BaseInfo>() {
                    @Override
                    public void onSuccess(BaseInfo baseInfo) {
                        ToastUtil.showToast(CreateMoveWareHouseSheetActivity.this, "创建成功");
                        /*if (baseInfo != null) {
                            if (baseInfo.getData() != null) {
                                Toast.makeText(CreateMoveWareHouseSheetActivity.this, "订单号:" + baseInfo.getData().getStoTfOrderNo(), Toast.LENGTH_SHORT).show();
                            }
                        }*/
                    }

                    @Override
                    public void onFailure(String msg) {
                        ToastUtil.showToast(CreateMoveWareHouseSheetActivity.this, msg);
                    }
                });
    }
}
